﻿
$(function(){
	
	window.Good = Backbone.Model.extend({
		defaults: {
			img: 'img/macbook-pro.png',
			qty: 1
		},
		initialize: function(m) {
			//console.log(m,this)
			this.save({'img': 'img/'+this.cid+'.png'});
		},
	});
  
    window.GoodList = Backbone.Collection.extend({
		model: Good,
		url: 'goods.jsp',
		Store: new Store('basket-items'),
	});

	window.Goods = new GoodList;
  
    var GoodView = Backbone.View.extend({
		tagName:  "tr",
		template: _.template($('#item-template').html()),
		events: {
			"click input.btn": "toBasket",
		},
		initialize: function() {
			//
		},
		render: function() {
		  this.$el.html(this.template(this.model.toJSON()));
		  return this;
		},
		toBasket: function(){
			var m = this.model.toJSON();
			var loc = Goods.Store.find({id:m.id});
			if (loc) m.qty+=loc.qty*1;
			Goods.Store.create(m);
			App.cntBasket()
		},
	});
  
	var AppView = Backbone.View.extend({
		el: $(".container"),
		initialize: function() {
			Goods.bind('reset', this.addAll, this);
			//Goods.reset([{"id":"45352",	"name":"Штуковина"},{"id":"1233245", "name":"Другая Штуковина"},{"id":"9865786", "name":"Мега Крутая Штуковина"}]);
			Goods.fetch()
	},
		addOne: function(item) {
			var view = new GoodView({model: item});
			this.$('#good-items-list').prepend(view.render().el);
		},
		addAll: function() {
		  Goods.each(this.addOne);
		},
		cntBasket: function(){
			this.$('#basketMenu').effect('highlight',{color:'#f93'},500)
			return
			var goods = _.pluck(Goods.Store.findAll(),'qty')
			var cnt = _.reduce(goods, function(memo, num){
				return memo + num;
			}, 0)
			this.$('#cntBasket').text(cnt)
		} 
	});

	window.App = new AppView;

});
